﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using AiXiu.Common;
using AiXiu.Model;
using AiXiu.BLL;

namespace AiXiu.WebSite
{
    public partial class EditUserInfo : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                TBUsers user = IdentityManager.ReadUser();

                txtNickName.Text = user.NickName;
                if (user.Hobby != null)
                {
                    var Hobbys = user.Hobby.Split(',');
                    foreach (string item in Hobbys)
                    {
                        if (chklHobby.Items.FindByValue(item) != null)
                            chklHobby.Items.FindByValue(item).Selected = true;
                    }
                }
                ddlSex.SelectedValue = user.Sex.ToString();
                hidAddress.Value = liAddress.InnerText = user.Address ?? "未知地";
                hidBirthday.Value = liBirthday.InnerText = user.Birthday.HasValue ? user.Birthday.Value.ToString("yyyy-MM-dd") : "未设置";
            }
        }

        protected void btnEdit_Click(object sender, EventArgs e)
        { 
            TBUsers newUser = IdentityManager.ReadUser();

            string hobbyStr = "";
            foreach (ListItem item in chklHobby.Items)
            {
                if (item.Selected)
                    hobbyStr += item.Value + ",";
            }
            newUser.Hobby = string.IsNullOrWhiteSpace(hobbyStr) ? null : hobbyStr.Substring(0, hobbyStr.Length - 1);

            newUser.Address = hidAddress.Value;
            newUser.Birthday = DateTime.Parse(hidBirthday.Value);
            newUser.NickName = txtNickName.Text;
            newUser.Sex = Convert.ToInt32(ddlSex.SelectedValue);

            OperResult rest = new UserManager().editUserInfo(newUser);
            if (rest.StatusCode == StatusCode.Succeed)
            {
                IdentityManager.SaveUser(newUser);
                this.AlertAndRedirect("succeedAlert", "修改成功", "Personal.aspx");
            }
            else
            {
                this.Alert("errorAlert", rest.Message);
            }
        }
    }
}